// pages/category/category.js
import {getCategory, getSubcategory, getCategoryDetail} from '../../service/category.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categories: {
      type: Array,
      value: []
    },
    categoryData: {
      type: Object,
      value: {}
    },
    currentIndex: 0
  },
  onLoad: function (options) {
    this._getCategory()
  },
  menuClick(e){
    const currentIndex = e.detail.index
    this.setData({
      currentIndex
    })
    //请求对应的类别数据
    this._getSubcategory(currentIndex)
    //请求对应的详情数据
    this._getCategoryDetail(currentIndex)
  },



  _getCategory(){
    getCategory().then(res => {
      //1.获取categories
      const categories = res.data.category.list
      //2.初始化每个类别的子数据
      const categoryData = {}
      for(let i = 0; i < categories.length; i++){
        categoryData[i] = {
          subCategories: [],
          categoryDetail: []
        }
      }
      //3.修改data中的数据
      this.setData({
        categories,
        categoryData
      })
      //4.请求第一个类别的数据
      this._getSubcategory(0)
      // 5.请求第一个类别的详情数据
      this._getCategoryDetail(0)
    })
  },
  _getSubcategory(currentIndex){
    const maitKey = this.data.categories[currentIndex].maitKey
    getSubcategory(maitKey).then(res => {
      const categoryDataTemp = this.data.categoryData
      categoryDataTemp[currentIndex].subCategories = res.data.list
      this.setData({
        categoryData: categoryDataTemp
      })
    })
  },
  _getCategoryDetail(currentIndex){
    //1.获取对应的miniWallKey
    const miniWallkey = this.data.categories[currentIndex].miniWallkey
    //2.请求数据类别的数据
    this._getRealCategoryDetail(currentIndex, miniWallkey, 'pop');    
  },
  _getRealCategoryDetail(index, miniWallkey, type){
    getCategoryDetail(miniWallkey, type).then(res => {
      //1.获取categoryData
      const categoryData = this.data.categoryData;
      //2.修改数据
      categoryData[index].categoryDetail = res
      //3.修改data中的数据
      this.setData({
        categoryData
      })
    })
  }
  
})